package com.example.usermanagement.service;

import com.example.usermanagement.entity.User;
import com.example.usermanagement.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;
import java.util.logging.Logger;

@Service
public class UserService {

    private static final Logger logger = Logger.getLogger(UserService.class.getName());

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private PasswordEncoder passwordEncoder;

    public User registerUser(User user) {
        Optional<User> existingUser = userRepository.findByUsername(user.getUsername());
        if (existingUser.isPresent()) {
            throw new RuntimeException("Username already exists: " + user.getUsername());
        }

        // 加密密码
        user.setPassword(passwordEncoder.encode(user.getPassword()));

        if (user.getRole() == null || user.getRole().isEmpty()) {
            user.setRole("USER");
        }

        return userRepository.save(user);
    }

    public Optional<User> loginUser(String username, String password) {
        logger.info("Attempting to login with username: " + username);
        Optional<User> userOptional = userRepository.findByUsername(username);
        if (userOptional.isPresent()) {
            logger.info("User found: " + username);
            User user = userOptional.get();
            logger.info("Stored password: " + user.getPassword());
            logger.info("Input password: " + password);

            // 使用 PasswordEncoder 验证密码
            if (passwordEncoder.matches(password, user.getPassword())) {
                logger.info("Password match successful");
                return userOptional;
            } else {
                logger.info("Password match failed");
            }
        } else {
            logger.info("User not found");
        }
        return Optional.empty();
    }

    public List<User> getAllUsers() {
        return userRepository.findAll();
    }

    public Optional<User> getUserById(Long id) {
        return userRepository.findById(id);
    }

    public User updateUser(User user) {
        Optional<User> existingUserOpt = userRepository.findById(user.getId());
        if (existingUserOpt.isPresent()) {
            User existingUser = existingUserOpt.get();

            // 保留密码字段不被覆盖（保持原有密码）
            if (user.getPassword() == null || user.getPassword().isEmpty()) {
                user.setPassword(existingUser.getPassword());
            } else {
                // 如果提供了新密码，则更新密码（加密）
                user.setPassword(passwordEncoder.encode(user.getPassword()));
            }

            // 保留用户名不变，避免重复检查
            user.setUsername(existingUser.getUsername());
        }

        return userRepository.save(user);
    }

    public void deleteUser(Long id) {
        userRepository.deleteById(id);
    }
}